package com.zut.chat.controller;

import com.zut.chat.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传图片
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("sessionId") String sessionId) {

        Map<String, Object> result = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            if (!fileUploadService.isImageFile(file)) {
                result.put("success", false);
                result.put("message", "只支持上传图片文件");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件大小
            if (!fileUploadService.isValidFileSize(file)) {
                result.put("success", false);
                result.put("message", "文件大小不能超过5MB");
                return ResponseEntity.badRequest().body(result);
            }

            // 上传文件
            String imageUrl = fileUploadService.uploadImage(file, sessionId);

            result.put("success", true);
            result.put("message", "上传成功");
            result.put("imageUrl", imageUrl);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("图片上传失败", e);
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
